<template>
<!-- 个人信息 -->
    <div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div class="boxx">
            <div class="box-1">
              <div class="box-2">
                <p class="p1" style="font-size: 20px">昵称<span><el-button type="text" class="xg" @click="openUpdateLoginName()">修改</el-button></span></p>
              </div>
              <p class="p2">{{tableDate.loginName}}</p>
            </div>  
            <div class="box-1">
              <div class="box-2">
                <p class="p1" style="font-size: 20px">收货地址<span>
                    <el-button type="text" class="xg" @click="openBindAddress()" v-show="showUpdate">绑定</el-button>
                    <el-button type="text" class="xg" @click="openUpdateAddress()" v-show="showBind">修改</el-button>
                  </span></p>
              </div>
              <div class="box-3" v-show="showBind">
                <el-descriptions class="margin-top" :column="3"  border>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-user"></i>
                      收件人
                    </template>
                    {{addressTableDate.name}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-mobile-phone"></i>
                      手机号
                    </template>
                    {{addressTableDate.phone}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-location-outline"></i>
                      地区
                    </template>
                    {{addressTableDate.district}}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-office-building"></i>
                      详细地址
                    </template>
                    {{addressTableDate.address}}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div> 
          </div>
          
        </el-card>
      <!-- 修改昵称弹窗 -->
        <el-dialog
          title="修改昵称"
          :visible.sync="updateLoginNameDialogVisible"
          width="30%"
          style="margin-top:30px"
          :before-close="closeExpertFormDialog"
          :append-to-body="shouldAppendToBody" >
            <el-form :model="form" :rules="updateForm" ref="form">
              <el-form-item label="用户昵称" style="width:300px" prop="loginName">
                <el-input v-model="form.loginName" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type="primary" @click="updateLoginName('form')">确 定</el-button>
          </span>
        </el-dialog>
      <!-- 修改收货地址弹窗 -->
        <el-dialog
          title="修改地址"
          :visible.sync="updateAddressDialogVisible"
          width="30%"
          style="margin-top:30px"
          :before-close="closeExpertFormDialogAddressForm"
          :append-to-body="shouldAppendToBody" >
            <el-form :model="addressForm" :rules="updateAddressForm" ref="addressForm">
              <el-form-item label="收件人" style="width:300px" prop="name">
                <el-input v-model="addressForm.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="手机号" style="width:300px" prop="phone">
                <el-input v-model="addressForm.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="地区" style="width:300px" prop="district">
                <area-cascader :level="1" type="text" placeholder="请选择地区" 
                    v-model='selected' :data="$pcaa"  class="area-cascader-selected">
                </area-cascader> 
              </el-form-item>
              <el-form-item label="详细地址" style="width:300px" prop="address">
                <el-input v-model="addressForm.address" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelAddress('addressForm')">取 消</el-button>
            <el-button type="primary" @click="updateAddress('addressForm')">确 定</el-button>
          </span>
        </el-dialog>
      <!-- 绑定收货地址弹窗 -->
        <el-dialog
          title="绑定地址"
          :visible.sync="bindAddressDialogVisible"
          width="30%"
          style="margin-top:30px"
          :before-close="closeExpertFormDialogAddressForm"
          :append-to-body="shouldAppendToBody" >
            <el-form :model="addressForm" :rules="updateAddressForm" ref="addressForm">
              <el-form-item label="收件人" style="width:300px" prop="name">
                <el-input v-model="addressForm.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="手机号" style="width:300px" prop="phone">
                <el-input v-model="addressForm.phone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="地区" style="width:300px" prop="district">
                <area-cascader :level="1" type="text" placeholder="请选择地区" 
                    v-model='selected' :data="$pcaa"  class="area-cascader-selected">
                </area-cascader> 
              </el-form-item>
              <el-form-item label="详细地址" style="width:300px" prop="address">
                <el-input v-model="addressForm.address" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelAddress('addressForm')">取 消</el-button>
            <el-button type="primary" @click="bindAddress('addressForm')">确 定</el-button>
          </span>
        </el-dialog>

    </div>
</template>
<script>
export default {
  name: 'PersonalInformation',
  data () {
    return {
        // 绑定收货地址弹窗
        bindAddressDialogVisible: false,
        // 判断是否绑定收货地址
        showUpdate: false,
        // 判断是否绑定收货地址
        showBind: false,
        // 全查收货地址数据
        addressTableDate: {
          name: '',
          phone: '',
          district: '',
          address: ''
        },
        // 修改收货地址表单规则
        updateAddressForm: {
          name: [
            { required: true, message: '请输入收件人', trigger: 'blur' },
            { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
          ],
          phone: [ { validator: this.validatorPhone, trigger: 'blur' }],
          district: [{validator: this.validatorDistrict, trigger: 'blur'}],
          address: [
            { required: true, message: '请输入详细地址', trigger: 'blur' },
            { min: 1, max: 80, message: '长度在 1 到 16 个字符', trigger: 'blur' }
          ]
        },
        // 修改收货地址表单数据
        addressForm: {},
        // 修改收货地址弹窗
        updateAddressDialogVisible: false,
        // selected: ['北京市','北京市','西城区'],
        selected: [],
        // 查询个人信息 
        tableDate: {},
        // 修改登录名弹窗
        updateLoginNameDialogVisible: false,
        // 是否将弹窗插入至 body 元素。默认将弹窗插入至 body 元素
        shouldAppendToBody: false,
        // 修改昵称表单数据
        form :{
          loginName: ''
        },
        // 修改昵称表单规则
        updateForm: {
          loginName:  [ { validator: this.validatorLoginName, trigger: 'blur' }]
        }
    }
  },
  mounted () {
    // 根据id查询用户信息
    this.selectUserbyId()
    // 根据用户id查询收货地址
    this.selectAddressById()
  },
  methods: {
    // 验证地区规则
    validatorDistrict(district, value, callback) {
      debugger
      console.log(this.selected)
      if (this.selected.length === 0 ) {
        callback(new Error('地区不能为空'));
      } else {
        callback();
      }
    },
    // 验证手机号格式，其他用户是否绑定
    validatorPhone(phone, value, callback) {
      // 验证手机号的正则表达式
      const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('输入正确手机号'))
        } else { 
          callback()
        }
      } else {
        callback()
      }
    },
    // 绑定地址
    bindAddress (formName) {
      console.log(window.sessionStorage.getItem('userId'))
      debugger
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.set('name', this.addressForm.name)
          formData.set('phone', this.addressForm.phone)
          formData.set('district', this.selected.toString())
          formData.set('address', this.addressForm.address)
          formData.set('userId', window.sessionStorage.getItem('userId'))
          this.$axios.put('/address/addAddress', formData)
            .then(res => {
              if (res.status === 200) {
                this.selectAddressById()
                this.updateAddressDialogVisible = false
                this.addressForm = {}
                this.message('success', '修改昵称成功')
              } else {
                this.message('warning', res.data.obj)
              }
            })
            // .then(() => {
            //   this.selectUserbyId()
            // })
            .catch(error => {
              console.log(error)
              this.message('warning', '对不起，修改失败！')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 修改绑定地址
    updateAddress (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.set('id', this.addressForm.id)
          formData.set('name', this.addressForm.name)
          formData.set('phone', this.addressForm.phone)
          formData.set('district', this.selected.toString())
          formData.set('address', this.addressForm.address)
          this.$axios.put('/address/updateAddress', formData)
            .then(res => {
              if (res.status === 200) {
                // this.updateLoginNameDialogVisible = false
                this.message('success', '修改昵称成功')
                this.selectAddressById()
                this.updateAddressDialogVisible = false
                // this.$eventBus.$emit('update-nickname-done')
                // this.selectUserbyId()
                // console.log(this.tableDate)
              } else {
                this.message('warning', res.data.obj)
              }
            })
            // .then(() => {
            //   this.selectUserbyId()
            // })
            .catch(error => {
              console.log(error)
              this.message('warning', '对不起，修改失败！')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 关闭修改地址按钮
    cancelAddress() {
      this.$refs.addressForm.resetFields()
      this.updateAddressDialogVisible = false
      this.bindAddressDialogVisible = false
      this.message('info', '已取消修改地址')
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialogAddressForm (done) {
      this.$refs.addressForm.resetFields()
      // done 用于关闭 Dialog
      done()
      this.message('info', '已取消修改地址')
    },
    // 打开修改地址弹窗
    openUpdateAddress () {
      this.addressForm = JSON.parse(JSON.stringify(this.addressTableDate))
      // if (this.addressTableDate.district !== '') {
        this.selected = this.addressTableDate.district.toString().split(',');
      // }        
      this.shouldAppendToBody = true
      this.updateAddressDialogVisible = true
    },
    // 打开绑定地址弹窗
    openBindAddress () { 
      // this.addressForm = this.addressTableDate
      // if (this.addressTableDate.district !== '') {
      //   this.selected = this.addressTableDate.district.toString().split(',');
      // }        
      this.shouldAppendToBody = true
      this.bindAddressDialogVisible = true
    },
    // 验证昵称格式，其他用户是否绑定
    validatorLoginName(loginName, value, callback) {
      debugger
      const reg = /^[\u4E00-\u9FA5a-zA-Z0-9_-]{4,20}$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('只能输入中文字、字母、数字、下划线和减号，并且长度为 4 到 20 个字符'))
        } else { 
          this.$axios.get('/user/selectUserByLoginName?loginName=' + value).then(res => {
            if (res.data.data !== null) {
              if (value === this.tableDate.loginName) {
                callback()
              } else {
                callback(new Error('当前昵称已存在'))
              }
            } else {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    },
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialog (done) {
      this.$refs.form.resetFields()
      // done 用于关闭 Dialog
      done()
      this.message('info', '已取消修改昵称')
    },
    // 修改昵称
    updateLoginName(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.set('id', this.tableDate.id)
          formData.set('loginName', this.form.loginName)
          this.$axios.put('/user/updateUserByLoginNameById', formData)
            .then(res => {
              if (res.status === 200) {
                this.updateLoginNameDialogVisible = false
                this.message('success', '修改昵称成功')
                this.$eventBus.$emit('update-nickname-done')
                this.selectUserbyId()
                console.log(this.tableDate)
              } else {
                this.message('warning', res.data.obj)
              }
            })
            // .then(() => {
            //   this.selectUserbyId()
            // })
            .catch(error => {
              console.log(error)
              this.message('warning', '对不起，修改失败！')
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 关闭修改昵称按钮
    cancel() {
      this.$refs.form.resetFields()
      this.updateLoginNameDialogVisible = false
      this.message('info', '已取消修改昵称')
    },
    // 打开修改昵称弹窗
    openUpdateLoginName () {
      this.form.loginName = this.tableDate.loginName                       
      this.shouldAppendToBody = true
      this.updateLoginNameDialogVisible = true
    },
    // 根据id查询用户信息
    selectUserbyId() {
      if (window.sessionStorage.getItem('userId') !== null) {
          this.$axios.get('/user/selectUserbyId?id=' + window.sessionStorage.getItem('userId')).then(res => {
          if(res.data.flag){
              this.tableDate = res.data.data
              console.log(this.tableDate)
              this.message('success', '获取用户个人信息成功')
          }else{
              this.message('error', '获取用户信息失败,请重新登录')
          }
      }).catch(err => {
          console.log(err)
      })
      } else {
            console.log(666)
      }
    },
    // 根据用户id查询收货地址
    selectAddressById() {
      if (window.sessionStorage.getItem('userId') !== null) {
          this.$axios.get('/address/selectAddressById?id=' + window.sessionStorage.getItem('userId')).then(res => {
          if(res.data.flag){
              this.addressTableDate = res.data.data
              console.log(this.addressTableDate)
              if (this.addressTableDate !== null) {
                this.message('success', '该用户已绑定收货地址')
                this.showBind = true
                this.showUpdate = false
              } else {
                this.message('success', '该用户未绑定收货地址')
                this.showBind = false
                this.showUpdate = true
                this.addressTableDate = {
                  name: '',
                  phone: '',
                  district: '',
                  address: ''
                }
              }
          }else{
              this.message('error', '获取用户收货地址失败,请重新登录')
          }
      }).catch(err => {
          console.log(err)
      })
      } else {
          console.log(666)
      }
    } 
  }
}
</script>

<style scoped>

  /* .area-selected-trigger{
    padding: 0px 20px 7px 12px
  } */
  .area-cascader-selected{
      width: 1px;
      line-height: 100%;
  }
  .box-3{
    width: 100%;
    height: 100%;
    float: left;
    /* background-color: royalblue; */
    margin-top: 40px;
    text-align: left;
  }
  .boxx{
    height: 600px;
  }
  .p2 {
    float: left;
    font-size: 26px;
    width: 100%;
    text-align: left;
    height: 60px;
    border-bottom:1px solid #ccc;
  }
  .box-2{
    width: 100%;
    height: 40px;
    float: left;
  }
  .xg{
    font-size: 16px;
    margin-left: 6px;
  }
  .p1{
    float: left;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .clearfix span{
    float: left;
  }
  .box-card {
    width: 900px;
    margin: 0 auto;
  }
  .box-1 {
    width: 100%;
    height: 120px;
    /* background-color: aqua; */
  }
</style>

